<?php
App::import('Vendor','Img_opt');
class MastersController extends AppController {
        
	var $name = 'Masters';
       
     
        var $helpers = array('Ajax','Time','html');
        
        var $components = array('RequestHandler');
      
	 function beforeFilter(){
             $user = $this->Session->read('Auth.User');
             if($user['activated']=='0'){
                  $this->redirect("/users/change"); 
             }
             
         }
        
        function inicio(){
             $user = $this->Session->read('Auth.User');
             //crea un archivo Log particular
             //$this->log($user , 'registro');
        }
        function admin_index(){
            
        }
        
        function agregar(){
            $this->set('title_for_layout', 'Agregar Secuestro');
            $this->loadModel('Charter');
            $this->loadModel('Province');
            $this->loadModel('Jurisdiction');
            $this->loadModel('Placement');
            $this->loadModel('Charter');
            $this->loadModel('Court');
            $this->loadModel('Secretary');
            $this->loadModel('VehiclesType');
            $this->loadModel('PoliceStation');
            $this->loadModel('Model');
            $this->loadModel('Brand');
            $this->loadModel('Upload');

            if(!empty($this->data)){    
                 $parafecha = explode("-", $this->data['Master']['date']);
                 $this->data['Master']['fecha']['year'] = $parafecha['0']; 
                 $this->data['Master']['fecha']['month'] = $parafecha['1'];
                 $this->data['Master']['fecha']['day'] = $parafecha['2'];
                 
                if (!empty($this->data['Master']['jurisdictions_id'])){
                $provinces2 = $this->Province->find('list',array('fields'=>'descripcion','conditions'=> array('jurisdiction_id'=>$this->data['Master']['jurisdictions_id'])));
                $provinces = $provinces2;
                }
                if (!empty($this->data['Master']['provinces_id'])){
                    $provinces_id = $this->data['Master']['provinces_id'];
                    $charters2 = $this->Charter->find('list', array('fields'=>array('Charter.id','Charter.descripcion'),'order'=>'provinces_id ASC','conditions'=>array('provinces_id'=>$provinces_id)));
                    $charters = $charters2;
                }
                if (!empty($this->data['Master']['charters_id'])){
                    $charters_id = $this->data['Master']['charters_id'];
                    $placements2 = $this->Placement->find('list', array('fields'=>array('Placement.id','Placement.descripcion'),'order'=>'id ASC','conditions'=>array('charters_id'=>$charters_id)));   
                    $placements = $placements2;
                }
                if (!empty($this->data['Master']['placements_id'])){
                    $placements_id = $this->data['Master']['placements_id'];
                    $courts2 = $this->Court->find('list', array('fields'=>array('Court.id','Court.descripcion'),'order'=>'id ASC','conditions'=>array('placements_id'=>$placements_id)));
                    $courts = $courts2;
                    //$this->set(compact('courts'));
                }
                if (!empty($this->data['Master']['courts_id'])){
                    $courts_id = $this->data['Master']['courts_id'];
                    $secretaries2 = $this->Secretary->find('list', array('fields'=>array('Secretary.id','Secretary.descripcion'),'order'=>'id ASC','conditions'=>array('courts_id'=>$courts_id)));
                    $this->log($secretaries2);
                    $secretaries = $secretaries2;
                    $this->set(compact('secretaries'));
                }
                if (!empty($this->data['Models']['brands_id'])){
                            $marca_id = $this->data['Models']['brands_id'];                
                            $models2 = $this->Model->find('list', array('fields'=>array('Model.id','Model.descripcion'),'order'=>'id ASC','conditions'=>array('brands_id'=>$marca_id)));
                            $models = $models2;
                }
                if (!empty($this->data['Vehicles']['extranjero'])){
                    $extranjero = $this->data['Vehicles']['extranjero'];
                }
                if (!empty($this->data['Vehicles']['dom_parcial'])){
                    $dom_parcial = $this->data['Vehicles']['dom_parcial'];
                }
                if (!empty($this->data['Vehicles']['motor_parc'])){
                    $motor_parc = $this->data['Vehicles']['motor_parc'];
                }
                if (!empty($this->data['Vehicles']['chasis_parc'])){
                    $chasis_parc = $this->data['Vehicles']['chasis_parc'];
                }
                $p_derecho = $this->data['uploads']["perfil_derecho"];
                $this->set(compact('parafecha','extranjero','dom_parcial','motor_parc','chasis_parc','p_derecho'));
            }    
                    
               //$secretaries = $this->Secretary->find('list',array('field'=>'descripcion'));    
            if(!isset($jurisdictions2)){$jurisdictions = $this->Jurisdiction->find('list',array('field'=>'descripcion'));}
               if(!isset($placements2)){$placements = $this->Placement->find('list',array('field'=>'descripcion'));} 
               if(!isset($models2)){$models = $this->Model->find('list',array('fields'=>'descripcion','order'=>'descripcion ASC'));}  
               if(!isset($charters2)){ $charters = $this->Charter->find('list');}  
               if(!isset($provinces2)){$provinces = $this->Province->find('list',array('fields'=>'descripcion'));}
               if(!isset($placements2)){$placements = $this->Placement->find('list',array('fields'=>'descripcion'));}
               if(!isset($courts2)){$courts = $this->Court->find('list',array('fields'=>'descripcion'));}

		$causes = $this->Master->Causes->find('list',array('fields'=>'nro_causa'));
		$vehicles = $this->Master->Vehicles->find('list',array('fields'=>'dominio'));
                //$states = $this->Master->PoliceState->find('list',array('fields'=>'descripcion','order'=>'descripcion DESC'));
                $desposits = $this->Master->Desposit->find('list',array('order'=>'descripcion ASC'));
                $vehicles_type = $this->VehiclesType->find('list',array('order'=>'descripcion ASC'));               
                $brands = $this->Brand->find('list',array('order'=>'descripcion ASC'));
                $police_stations = $this->PoliceStation->find('list',array('order'=>'descripcion ASC'));
                $states['1'] = 'Secuestrado';
		$this->set(compact('situations', 
                        'causes', 'requests', 'vehicles',
                        'states','desposits','vehicles_type',
                        'brands','models','jurisdictions','placements',
                        'provinces','charters','police_stations','courts','secretaries'));
        }
        
        function index() {
                $this->set('title_for_layout', 'Listar Secuestros');
		$this->Master->recursive = 0;
                if(!$this->checkAccess()){ 
                 $this->paginate = array( 
                            'conditions' => 'Master.police_states_id = 1'                                
                           ); 
                }
		$this->set('masters', $this->paginate());
                $states = $this->Master->PoliceState->find('list',array('fields'=>'descripcion'));
                $deposits = $this->Master->Desposit->find('list');
               
                $this->set(compact('states','deposits'));
	}

	function view($id = null) {
                $this->set('title_for_layout', 'Ver Secuestro');
		if (!$id) {
			$this->Session->setFlash(__('Invalid master', true));
			$this->redirect(array('action' => 'index'));
		}
                $this->loadModel('Charter');
                $this->loadModel('Province');
                $this->loadModel('Jurisdiction');
                $this->loadModel('Placement');
                $this->loadModel('Charter');
                $this->loadModel('Court');
                $this->loadModel('Secretary');
                $this->loadModel('VehiclesType');
                $this->loadModel('PoliceStation');
                $this->loadModel('Model');
                $this->loadModel('Brand');
                $this->loadModel('Upload');
                $this->loadModel('PoliceState');
                $this->loadModel('State');
                $master = $this->Master->read(null, $id);
               
                $vehicles = $this->Master->Vehicles->find('all',array('conditions' => array('Vehicles.id'=>$master['Vehicles']['id'])));
                $vehicles_type = $this->VehiclesType->find('all',array('conditions' => array('VehiclesType.id'=>$vehicles['0']['Vehicles']['vehicles_types_id']),'fields'=>array('id','descripcion')));
                $models = $this->Model->find('all',array('conditions' => array('Model.id'=>$vehicles['0']['Vehicles']['models_id'])));
                $brands = $this->Brand->find('all',array('conditions' => array('Brand.id'=>$models['0']['Model']['brands_id']),'fields'=>array('id','descripcion')));  
               
                $causes = $this->Master->Causes->find('all',array('conditions' => array('Causes.id'=>$master['Causes']['id'])));
                $secretaries = $this->Secretary->find('all',array('conditions' => array('Secretary.id'=>$causes['0']['Causes']['secretaries_id'])));
                $courts = $this->Court->find('all',array('conditions' => array('Court.id'=>$secretaries ['0']['Secretary']['courts_id']),'fields'=>array('id','descripcion','placements_id')));
                $placements = $this->Placement->find('all',array('conditions' => array('Placement.id'=>$courts['0']['Court']['placements_id']),'fields'=>array('id','descripcion','charters_id')));
          
                $charters = $this->Charter->find('all',array('conditions' => array('Charter.id'=>$placements['0']['Placement']['charters_id']),'fields'=>array('id','descripcion','jurisdictions_id','provinces_id')));
                $jurisdictions = $this->Jurisdiction->find('all',array('conditions' => array('Jurisdiction.id'=>$charters['0']['Charter']['jurisdictions_id']),'fields'=>array('id','descripcion')));
                $provinces = $this->Province->find('all',array('conditions' => array('Province.id'=>$charters['0']['Charter']['provinces_id']),'fields'=>array('id','descripcion')));
//              si es admin le paso a la vista el Estado de Pronacom sino el estado de la policia  
                if($this->checkAccess()){ 
                    $policestate = $this->Master->PoliceState->find('all',array('conditions' => array('PoliceState.id'=>$this->data['Master']['police_states_id']),'fields'=>array('id','descripcion'))); 
                    //$this->set($police_states,'police_states');
                }
                $states = $this->Master->State->find('all',array('conditions' => array('State.id'=>$this->data['Master']['states_id']),'fields'=>array('id','descripcion')));   
                 
                $image = $this->Upload->find('all',array('conditions'=>array('Upload.masters_id'=>$id),'fields'=>'id'));
                if(!empty($image)){
                $item = $image['0']['Upload']['id'];
                }else{
                    $item='1';
                }
                    $this->set(compact('master', 'causes','vehicles','vehicles_type','models','brands','image',
                                   'jurisdictions','placements','charters','courts','secretaries','provinces','item'));
	
                if($this->checkAccess()){
                    $this->render('viewadmin');
                }
        }

	function add() {
            $this->set('title_for_layout', 'Nuevo Secuestro');
            $this->loadModel('Charter');
            $this->loadModel('Province');
            $this->loadModel('Jurisdiction');
            $this->loadModel('Placement');
            $this->loadModel('Charter');
            $this->loadModel('Court');
            $this->loadModel('Secretary');
            $this->loadModel('VehiclesType');
            $this->loadModel('PoliceStation');
            $this->loadModel('Model');
            $this->loadModel('Brand');
            $this->loadModel('Upload');
      if (!empty($this->data)){
          
      if ($this->valida($this->data)){     
 
                    // Guardando los datos del vehiculo      
                    if (!empty($this->data['Vehicles']['dominio'])){
                        $this->Master->Vehicles->create();
                        if ($this->Master->Vehicles->save($this->data)) {
                                $this->data['Master']['vehicles_id'] = $this->Master->Vehicles->getLastInsertId();
                                $this->data['Master']['rodamiento'] = $this->data['Vehicles']['rodamiento'];
	                        //$this->Session->setFlash(__('The vehicle has been saved', true));
			}else{
                               
				//$this->Session->setFlash(__('The vehicle could not be saved. Please, try again.', true));
			}
                    }
//////////////////////////////////////////////////////////////////////////
                     //Guardando datos de la Causa
                     if (!empty($this->data['Causes']['nro_causa'])) {
                         $this->Master->Causes->create();
                                if ($this->Master->Causes->save($this->data)) {

                                $this->data['Master']['causes_id'] = $this->Master->Causes->getLastInsertId();
                                	          
                                //$this->Session->setFlash(__('The cause has been saved', true));
                                //$this->redirect(array('action' => 'index'));
			} 
                     }
                    
                     //Guardar imagen
                     if($this->data['Master']['file']['size']){
                         $date = getdate();
                     $this->data['Master']['file']['name'] =  $date['year'].'_'.$date['mon'].'_'.$date['mday'].'_'.$date['hours'].'_'.$date['minutes'].'_'.$date ['seconds'].$this->data['Master']['file']['name'];   
                     if(move_uploaded_file($this->data['Master']['file']['tmp_name'],'img/fotos/'.$this->data['Master']['file']['name'])){
                            $this->log('subido');
                             if($this->Upload->save($this->data['Master']['file'])) {
                                   $this->log('salvado');
                                   $this->data['Master']['uploads_id'] = $this->Upload->getLastInsertId();
                            }else{
                                $this->log('NO salvado');  
                     
                     }
                     }else{
                         $this->log('no subido');
                          }
                     }
  
		     //guardando datos del secuestro	
                     if($this->data['Master']['causes_id'] && $this->data['Master']['vehicles_id']){
                     $this->Master->create();
                     $date = getdate();
                     $this->data['Master']['fecha_registro'] =  $date['year'].'-'.$date['mon'].'-'.$date['mday'].' '.$date['hours'].':'.$date['minutes'].':'.$date ['seconds'];
                     $user = $this->Session->read('User');
                     $this->data['Master']['user_id'] = $user['id'];
                                         

			if ($this->Master->save($this->data)) {
				$this->Session->setFlash(__('The master has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
			}
                     }else{
                         $this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
                         $provinces2 = $this->Province->find('list',array('fields'=>'descripcion','conditions'=> array('jurisdiction_id'=>$this->data['Master']['jurisdictions_id'])));
                         $provinces = $provinces2;
                         $this->set(compact('provinces'));
                         
                     }
                
      }else{
          
            if (!empty($this->data['Master']['jurisdictions_id'])){
            $provinces2 = $this->Province->find('list',array('fields'=>'descripcion','conditions'=> array('jurisdiction_id'=>$this->data['Master']['jurisdictions_id'])));
            $provinces = $provinces2;
            }
            if (!empty($this->data['Master']['provinces_id'])){
                 $provinces_id = $this->data['Master']['provinces_id'];
                 $charters2 = $this->Charter->find('list', array('fields'=>array('Charter.id','Charter.descripcion'),'order'=>'provinces_id ASC','conditions'=>array('provinces_id'=>$provinces_id)));
                 $charters = $charters2;
            }
            if (!empty($this->data['Master']['charters_id'])){
                   $charters_id = $this->data['Master']['charters_id'];
                   $placements2 = $this->Placement->find('list', array('fields'=>array('Placement.id','Placement.descripcion'),'order'=>'id ASC','conditions'=>array('charters_id'=>$charters_id)));   
                   $placements = $placements2;
            }
            if (!empty($this->data['Master']['placements_id'])){
                   $placements_id = $this->data['Master']['placements_id'];
                   $courts2 = $this->Court->find('list', array('fields'=>array('Court.id','Court.descripcion'),'order'=>'id ASC','conditions'=>array('placements_id'=>$placements_id)));
                   $courts = $courts2;
                   //$this->set(compact('courts'));
            }
            if (!empty($this->data['Master']['courts_id'])){
                   $courts_id = $this->data['Master']['courts_id'];
                   $secretaries2 = $this->Secretary->find('list', array('fields'=>array('Secretary.id','Secretary.descripcion'),'order'=>'id ASC','conditions'=>array('courts_id'=>$courts_id)));
                   $secretaries = $secretaries2;
                   $this->set(compact('secretaries'));
            }
             if (!empty($this->data['Models']['brands_id'])){
                        $marca_id = $this->data['Models']['brands_id'];                
                        $models2 = $this->Model->find('list', array('fields'=>array('Model.id','Model.descripcion'),'order'=>'id ASC','conditions'=>array('brands_id'=>$marca_id)));
                        $models = $models2;
            }
           
           
           
      }
 
                   
   }//if de datos
               if(!isset($jurisdictions2)){$jurisdictions = $this->Jurisdiction->find('list',array('field'=>'descripcion'));}
               if(!isset($placements2)){$placements = $this->Placement->find('list',array('field'=>'descripcion'));} 
               if(!isset($models2)){$models = $this->Model->find('list',array('fields'=>'descripcion','order'=>'descripcion ASC'));}  
               if(!isset($charters2)){ $charters = $this->Charter->find('list');}  
               if(!isset($provinces2)){$provinces = $this->Province->find('list',array('fields'=>'descripcion'));}
		$causes = $this->Master->Causes->find('list',array('fields'=>'nro_causa'));
		$vehicles = $this->Master->Vehicles->find('list',array('fields'=>'dominio'));
                $states = $this->Master->State->find('list',array('order'=>'descripcion ASC'));
                $desposits = $this->Master->Desposit->find('list',array('order'=>'descripcion ASC'));
                $vehicles_type = $this->VehiclesType->find('list',array('order'=>'descripcion ASC'));               
                $brands = $this->Brand->find('list',array('order'=>'descripcion ASC'));
                $police_stations = $this->PoliceStation->find('list',array('order'=>'descripcion ASC'));

                
		$this->set(compact('situations', 
                        'causes', 'requests', 'vehicles',
                        'states','desposits','vehicles_type',
                        'brands','models','jurisdictions','placements',
                        'provinces','charters','police_stations','courts'));
	}
        
        function update_select(){
             $this->loadModel('Model');
             if (!empty($this->data['Models']['brands_id'])){
                        $marca_id = $this->data['Models']['brands_id'];                
                        $modelos = $this->Model->find('all', array('fields'=>array('Model.id','Model.descripcion'),'order'=>'id ASC','conditions'=>array('brands_id'=>$marca_id)));
                }
             else{
                        $modelos = $this->Model->find('all', array('fields'=>array('Models.descripcion'),'order'=>'id ASC'));
                }
              $this->set('options', Set::combine($modelos, "{n}.Model.id","{n}.Model.descripcion"));
              $this->render('/masters/update_select', 'ajax');
        }
        
        function update_placements(){
          $this->loadModel('Placement');
             if (!empty($this->data['Master']['charters_id'])){
                
                   $charters_id = $this->data['Master']['charters_id'];
                   $placements = $this->Placement->find('all', array('fields'=>array('Placement.id','Placement.descripcion'),'order'=>'id ASC','conditions'=>array('charters_id'=>$charters_id)));
             }else{
                  $placements = $this->Placement->find('all', array('fields'=>array('placement.descripcion'),'order'=>'id ASC'));
             }
                $this->set('options', Set::combine($placements, "{n}.Placement.id","{n}.Placement.descripcion"));
                $this->render('/masters/update_select', 'ajax'); 
        }

        function update_provinces(){
           $this->loadModel('Charter');
           if (!empty($this->data['Master']['provinces_id'])){
                 $provinces_id = $this->data['Master']['provinces_id'];
                 $charters = $this->Charter->find('all', array('fields'=>array('Charter.id','Charter.descripcion'),'order'=>'provinces_id ASC','conditions'=>array('provinces_id'=>$provinces_id)));
           }else{
                 $charters = $this->Charter->find('all', array('fields'=>array('Charter.descripcion'),'order'=>'id ASC'));
           }
                $this->set('options', Set::combine($charters, "{n}.Charter.id","{n}.Charter.descripcion"));
                $this->render('/masters/update_select', 'ajax');
        }
        
        function update_jurisdictions(){
           $this->loadModel('Province');
           if (!empty($this->data['Master']['jurisdictions_id'])){
               $jurisdiction_id = $this->data['Master']['jurisdictions_id'];
               $provinces = $this->Province->find('all', array('fields'=>array('Province.id','Province.descripcion'),'order'=>'id ASC','conditions'=>array('jurisdiction_id'=>$jurisdiction_id)));
           }else{
               $provinces = array();    
           }                
           $this->set('options', Set::combine($provinces, "{n}.Province.id","{n}.Province.descripcion"));
           $this->render('/masters/update_select', 'ajax');
        }
        
        function update_courts(){
             $this->loadModel('Court');
             if (!empty($this->data['Master']['placements_id'])){
                   $placements_id = $this->data['Master']['placements_id'];
                   $courts = $this->Court->find('all', array('fields'=>array('Court.id','Court.descripcion'),'order'=>'length(Court.descripcion),Court.descripcion ASC','conditions'=>array('placements_id'=>$placements_id)));
                   }else{
                  $courts = $this->Court->find('all', array('fields'=>array('Court.descripcion'),'order'=>'id ASC'));
             }
                $this->set('options', Set::combine($courts, "{n}.Court.id","{n}.Court.descripcion"));
                $this->render('/masters/update_select', 'ajax'); 
        } 
       
        function update_secretaries(){
             $this->loadModel('Secretary');
             if (!empty($this->data['Master']['courts_id'])){
                   $courts_id = $this->data['Master']['courts_id'];
                   $secretaries = $this->Secretary->find('all', array('fields'=>array('Secretary.id','Secretary.descripcion'),'order'=>'id ASC','conditions'=>array('courts_id'=>$courts_id)));
             }else{
                  $secretaries = $this->Secretary->find('all', array('fields'=>array('Secretary.descripcion'),'order'=>'id ASC'));
             }
                $this->set('options', Set::combine($secretaries, "{n}.Secretary.id","{n}.Secretary.descripcion"));
                $this->render('/masters/update_select', 'ajax');    
        }
        
	function edit($id = null) {
                $this->loadModel('Charter');
                $this->loadModel('Province');
                $this->loadModel('Jurisdiction');
                $this->loadModel('Placement');
                $this->loadModel('Charter');
                $this->loadModel('Court');
                $this->loadModel('Secretary');
                $this->loadModel('VehiclesType');
                $this->loadModel('PoliceStation');
                $this->loadModel('Model');
                $this->loadModel('Brand');
                
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid master', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Master->save($this->data)) {
				$this->Session->setFlash(__('The master has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Master->read(null, $id);
		}
		//$situations = $this->Master->Situation->find('list');
		$causes = $this->Master->Causes->find('list',array('fields'=>'nro_causa'));
		$requests = $this->Master->Requests->find('list');
		$vehicles = $this->Master->Vehicles->find('list',array('fields'=>'dominio'));
               
                $states = $this->Master->State->find('list');
                $desposits = $this->Master->Desposit->find('list');
                $master = $this->data['Master'];
                $jurisdictions = $this->Jurisdiction->find('list',array('field'=>'descripcion'));
                $placements = $this->Placement->find('list',array('field'=>'descripcion'));
		$requests = $this->Master->Requests->find('list');
                $vehicles_type = $this->VehiclesType->find('list',array('order'=>'id DESC'));
                $models = $this->Model->find('list',array('fields'=>'descripcion'));
                $brands = $this->Brand->find('list');
                $provinces = $this->Province->find('list');
                $charters = $this->Charter->find('list');
                $police_stations = $this->PoliceStation->find('list');
				$this->set(compact('situations', 
                        'causes', 'requests', 'vehicles',
                        'states','desposits','vehicles_type',
                        'brands','models','jurisdictions','placements',
                        'provinces','charters','police_stations','master'));
	
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for master', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Master->delete($id)) {
			$this->Session->setFlash(__('Master deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Master was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
        
        function legajo($id = null) {
                
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid master', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Master->save($this->data)) {
				$this->Session->setFlash(__('The master has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Master->read(null, $id);
                        if($this->data['Master']['fecha_compactacion']==''){
                            
                            $tiene_fecha_c = '0';
                        }else{
                            $tiene_fecha_c = '1';
                        }
                        
		}
		//$situations = $this->Master->Situation->find('list');
		
                $master = $this->data['Master'];
             
                $this->set(compact('master','tiene_fecha_c'));
	
	}
        function valida(array $array) {
            foreach ($this->data['Master']['fecha'] as $fecha) {
                if (empty($fecha)){
                $this->Session->setFlash(__('Los campos Fecha secuestro deben estar completos', true)); 
                return false;
                } 
            }

           if (empty($this->data['Vehicles']['vehicles_types_id'])){
               $this->Session->setFlash(__('El campo Tipo de Vehículo no puede estar vacio', true)); 
               return false;
           }
           if (empty($this->data['Models']['brands_id'])){
               $this->Session->setFlash(__('El campo Marca no puede estar vacio', true)); 
               return false;
           }
           if(empty($this->data['Vehicles']['models_id'])){
               $this->Session->setFlash(__('El campo Dominio no puede estar vacio', true));
               return false;
           }
           if($this->data['Vehicles']['dom_parcial']=='0' || $this->data['Vehicles']['dom_parcial']=='1'){
                if(empty($this->data['Vehicles']['dominio'])){
                    $this->Session->setFlash(__('El campo Dominio no puede estar vacio', true));
                    return false;
                    }
           }
           if($this->data['Vehicles']['motor_parc']=='0' || $this->data['Vehicles']['motor_parc']=='1'){
                if(empty($this->data['Vehicles']['nro_motor'])){
                    $this->Session->setFlash(__('El campo Nro de Motor no puede estar vacio', true));
                    return false;
                    }
           }
           if($this->data['Vehicles']['chasis_parc']=='0' || $this->data['Vehicles']['chasis_parc']=='1'){
                if(empty($this->data['Vehicles']['nro_chasis'])){
                    $this->Session->setFlash(__('El campo Nro de Chasis no puede estar vacio', true));
                    return false;
                    }
           }
           if ($this->data['Master']['jurisdictions_id']==''){
               $this->Session->setFlash(__('El campo Jurisdicción no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['charters_id']==''){
               $this->Session->setFlash(__('El campo Fuero no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['placements_id']==''){
               $this->Session->setFlash(__('El campo Depto. Judicial o Circunscripción no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['courts_id']==''){
               $this->Session->setFlash(__('El campo Juzgado no puede estar vacio', true)); 
               return false;
           } 
           if ($this->data['Causes']['secretaries_id']==''){
               $this->Session->setFlash(__('El campo Secretaria no puede estar vacio', true));
               return false;
           } 
           if (empty($this->data['Causes']['police_stations_id'])){
               $this->Session->setFlash(__('El campo dependencia Policial no puede estar vacio', true)); 
               return false;
           }
           if (empty($this->data['Causes']['nro_causa'])){
               //$this->log($this->data['Master']['Causes']['nro_causa']);
               $this->Session->setFlash(__('El campo N° de Causa no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['carpeta']==''){
               $this->Session->setFlash(__('El campo Carpeta no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['auditoria']==''){
               $this->Session->setFlash(__('El campo Auditoria no puede estar vacio', true)); 
               return false;
           } 
           if ($this->data['Master']['pericia']==''){
               $this->Session->setFlash(__('El campo Pericia no puede estar vacio', true)); 
               return false;
           } 
           if ($this->data['Master']['pericia']=='1'){
               if ($this->data['Vehicles']['rodamiento']==''){
               $this->Session->setFlash(__('El campo Rodamiento no puede estar vacio', true)); 
               return false;
               }
           } 
//           if (empty($this->data['Master']['foto'])){
//               $this->Session->setFlash(__('El campo Estado del Vehículo no puede estar vacio', true)); 
//               return false;
//           }
           if (empty($this->data['Master']['caja_archivo'])){
               $this->Session->setFlash(__('El campo Caja Archivo no puede estar vacio', true)); 
               return false;
           } 
           if (empty($this->data['Master']['states_id'])){
                $this->Session->setFlash(__('El campo Estado del Vehículo no puede estar vacio', true)); 
               return false;
           }
           if ($this->data['Master']['desposits_id']==''){               
                    $this->Session->setFlash(__('El campo Depósito no puede estar vacio', true)); 
                    return false;           
                }
           
            return true;

        }
        function sube_imagenes(){
                 // subir las imagenes a la DB pero antes redimensionarla a 640x480
                 $this->data['uploads']['masters_id'] = $this->Master->id;
                 

                  //////////////perfil derecho////////////////
                  $name = $this->data['uploads']["perfil_derecho"];//para guardar el nombre del archivo
                  $gestor = fopen('img/fotos/'.$this->data['uploads']["perfil_derecho"],"r");//abro archivo
                  $fileData = fread($gestor,filesize('img/fotos/'.$this->data['uploads']["perfil_derecho"]));//leo archivo
                  $this->data['uploads']['perfil_derecho'] = $fileData;//guardo el archivo en esa variable para guardar datos binarios en la DB
                  fclose($gestor);//cierro archivo
                 //aca seria eliminar los archivos ya subidos 
                  $filename = 'img/fotos/'.$name;//obtengo ruta del archivo
                  unlink($filename);//elimino el archivo
                  
////                  //////////////perfil izquierdo////////////////
                  $name_iz = $this->data['uploads']["perfil_izquierdo"];
                  $gestor_iz = fopen('img/fotos/'.$this->data['uploads']["perfil_izquierdo"],"r");
                  $fileData_iz = fread($gestor_iz,filesize('img/fotos/'.$this->data['uploads']["perfil_izquierdo"]));
                  $this->data['uploads']['perfil_izquierdo'] = $fileData_iz;
                  fclose($gestor_iz);
                 //aca seria eliminar los archivos ya subidos 
                  $filename_iz = 'img/fotos/'.$name_iz;
                  unlink($filename_iz);
//                  
//                  ////////////////frente///////////////////////////
                  $name_fr = $this->data['uploads']["frente"];
                  $gestor_fr = fopen('img/fotos/'.$this->data['uploads']["frente"],"r");
                  $fileData_fr = fread($gestor_fr,filesize('img/fotos/'.$this->data['uploads']["frente"]));
                  $this->data['uploads']['frente'] = $fileData_fr;
                  fclose($gestor_fr);
                 //aca seria eliminar los archivos ya subidos 
                  $filename_fr = 'img/fotos/'.$name_fr;
                  unlink($filename_fr);
                 
////                //////////////Baul////////////////////
                  $name_bl = $this->data['uploads']["baul"];
                  $gestor_bl = fopen('img/fotos/'.$this->data['uploads']["baul"],"r");
                  $fileData_bl = fread($gestor_bl,filesize('img/fotos/'.$this->data['uploads']["baul"]));
                  $this->data['uploads']['baul'] = $fileData_bl;
                  fclose($gestor_bl);
                 //aca seria eliminar los archivos ya subidos 
                  $filename_bl = 'img/fotos/'.$name_bl;
                  unlink($filename_bl);
                  
////                //////////////Interior////////////////
                  $name_in = $this->data['uploads']["interior"];
                  $gestor_in = fopen('img/fotos/'.$this->data['uploads']["interior"],"r");
                  $fileData_in = fread($gestor_in,filesize('img/fotos/'.$this->data['uploads']["interior"]));
                  $this->data['uploads']['interior'] = $fileData_in;
                  fclose($gestor_in);
                 //aca seria eliminar los archivos ya subidos 
                  $filename_in = 'img/fotos/'.$name_in;
                  unlink($filename_in);
                  
////                //////////////Motor////////////////
                  $name_mt = $this->data['uploads']["motor"];
                  $gestor_mt = fopen('img/fotos/'.$this->data['uploads']["motor"],"r");
                  $fileData_mt = fread($gestor_mt,filesize('img/fotos/'.$this->data['uploads']["motor"]));
                  $this->data['uploads']['motor'] = $fileData_mt;
                  fclose($gestor_mt);
                 //aca seria eliminar los archivos ya subidos 
                  $filename_mt = 'img/fotos/'.$name_mt;
                  unlink($filename_mt);
                  
              //    $this->log($this->data['uploads']);
                  $this->log('antes de create');
                  $this->Master->Upload->create();
                  
                  
                  if($this->Master->Upload->save($this->data['uploads'])){
                      $this->log('salvado OK');
                      return true;
                  }else{
                      return false;
                  }
                     
        }
        function valida_imagenes(){
            return true;
            if($this->data['uploads']['perfil_derecho']['error']== 0){
                
                return true;
            }
            elseif($this->data['uploads']['perfil_izquierdo']['error']== 0){
                return false;
            }
            elseif($this->data['uploads']['frente']['error']== 0){
                return false;
            }
            elseif($this->data['uploads']['baul']['error']== 0){
                return false;
            }
            elseif($this->data['uploads']['interior']['error']== 0){
                return false;
            }
            elseif($this->data['uploads']['motor']['error']== 0){
                return false;
            }else{
                return true;
            }
            
        }
        function resize_image($name,$tmp_name){
            move_uploaded_file($tmp_name, "img/fotos/$name");
            $obj = new Img_opt();
            // setea maximo width su supera sera redimensionada
            $obj->max_width(640);
            // setea maximo height si supera sera redimensionada
            // for example size of the area in which image to be displayed
            $obj->max_height(480);
            $obj->image_path("img/fotos/$name");
             // llamar al metodo resize()
            $obj->image_resize();
            $gestor = fopen("img/fotos/$name","r");
            $contenido = fread($gestor, filesize( "img/fotos/$name"));
            $path = $obj->path;
            fclose($gestor);
            //eliminar archivo 
            //unlink($path);
            return $contenido;

        }
        
 //funcion para ajax valida tipo de imagen       
        function update_image(){    
             $this->loadModel('Upload');
             if($this->data['uploads'])
             $arreglo = $this->data['uploads'];
             foreach($arreglo as $var){
                 $dato = $var;
             } 
            $imagen = explode( ".", $dato );
            if($imagen[1]=='jpeg'||$imagen[1]=='jpg'||$imagen[1]=='JPG'){
                $error='';
            }else{
                $error='el tipo de imagen debe ser JPG';
            }
              $this->set('error',$error);
              $this->render('/masters/update_image', 'ajax');
        }
        function confirma(){
            $this->layout = 'sin_menu';
           // Configure::write('debug', '0'); //para desactivar debugger
               if(!empty($this->data)){  
                 $this->loadModel('Charter');
                 $this->loadModel('Province');
                 $this->loadModel('Jurisdiction');
                 $this->loadModel('Placement');
                 $this->loadModel('Charter');
                 $this->loadModel('Court');
                 $this->loadModel('Secretary');
                 $this->loadModel('VehiclesType');
                 $this->loadModel('PoliceState');
                 $this->loadModel('Model');
                 $this->loadModel('PoliceStation');
                 $this->loadModel('Desposit');
                 $this->loadModel('Brand');
                 $this->loadModel('Upload');
                   $date = $this->data['Master']['fecha']['year'].'-'.$this->data['Master']['fecha']['month'].'-'.$this->data['Master']['fecha']['day'];
                   $jurisdictions = $this->Jurisdiction->find('all',array('conditions' => array('Jurisdiction.id'=>$this->data['Master']['jurisdictions_id']),'fields'=>array('id','descripcion')));
                   $provinces = $this->Province->find('all',array('conditions' => array('Province.id'=>$this->data['Master']['provinces_id']),'fields'=>array('id','descripcion')));
                   $charters = $this->Charter->find('all',array('conditions' => array('Charter.id'=>$this->data['Master']['charters_id']),'fields'=>array('id','descripcion','jurisdictions_id','provinces_id'))); 
                   $courts = $this->Court->find('all',array('conditions' => array('Court.id'=>$this->data['Master']['courts_id']),'fields'=>array('id','descripcion','placements_id')));
                   $placements = $this->Placement->find('all',array('conditions' => array('Placement.id'=>$this->data['Master']['placements_id']),'fields'=>array('id','descripcion','charters_id')));
                   $causes = $this->data['Causes']['nro_causa'];
                   $desc_cause = $this->data['Causes']['descripcion'];
                   $secretaries = $this->Secretary->find('all',array('conditions' => array('Secretary.id'=>$this->data['Causes']['secretaries_id'])));
                   
                   $dom_extran = $this->data['Vehicles']['extranjero'];
                   $dom_compl = $this->data['Vehicles']['dom_parcial'];
                   $dominio = $this->data['Vehicles']['dominio'];
                   $motor_compl = $this->data['Vehicles']['motor_parc'];
                   $nro_motor = $this->data['Vehicles']['nro_motor'];
                   $chasis_compl = $this->data['Vehicles']['chasis_parc'];
                   $chasis = $this->data['Vehicles']['nro_chasis'];
                   
                   $vehicles_type = $this->VehiclesType->find('all',array('conditions' => array('VehiclesType.id'=>$this->data['Vehicles']['vehicles_types_id']),'fields'=>array('id','descripcion')));
                   $models = $this->Model->find('all',array('conditions' => array('Model.id'=>$this->data['Vehicles']['models_id'])));
                   $brands = $this->Brand->find('all',array('conditions' => array('Brand.id'=>$this->data['Models']['brands_id']),'fields'=>array('id','descripcion')));  
               
                   $states = $this->PoliceState->find('all',array('conditions' => array('PoliceState.id'=>$this->data['Master']['police_states_id']),'fields'=>array('id','descripcion'))); 
                   $desposits = $this->Desposit->find('all',array('conditions' => array('Desposit.id'=>$this->data['Master']['desposits_id']),'fields'=>array('id','descripcion')));  
                   $observaciones = $this->data['Master']['observaciones ']; 
                 
                  //$perfil_derecho = $this->data['uploads']['perfil_derecho'];
                  $p_derecho = $this->data['uploads']['perfil_derecho'];
                  //$fileData = $this->resize_image($perfil_derecho["name"],$perfil_derecho["tmp_name"]);
                  
                  //$perfil_izquierdo = $this->data['uploads']['perfil_izquierdo'];
                  $p_izquierdo = $this->data['uploads']['perfil_izquierdo'];
                  //$fileData = $this->resize_image($perfil_izquierdo["name"],$perfil_izquierdo["tmp_name"]);
                  
                  //$frente = $this->data['uploads']['frente'];
                  $p_frente = $this->data['uploads']['frente'];
                  //$fileData = $this->resize_image($frente["name"],$frente["tmp_name"]);
                  
                  //$baul = $this->data['uploads']['baul'];
                  $p_baul = $this->data['uploads']['baul'];
                  //$fileData = $this->resize_image($baul["name"],$baul["tmp_name"]);
                  
                  //$interior = $this->data['uploads']['interior'];
                  $p_interior = $this->data['uploads']['interior'];
                  //$fileData = $this->resize_image($interior["name"],$interior["tmp_name"]);
                  
                  //$motor = $this->data['uploads']['motor'];
                  $p_motor = $this->data['uploads']['motor'];
                  //$fileData = $this->resize_image($motor["name"],$motor["tmp_name"]);
                   
                  $this->set(compact('date','jurisdictions','provinces','charters','courts','placements','causes','secretaries',
                                      'dom_extran','dom_compl','dominio','motor_compl','nro_motor','chasis_compl','chasis','vehicles_type',
                                      'brands','models','desc_cause','states','desposits','observaciones','p_derecho','p_izquierdo',
                                      'p_frente','p_baul','p_interior','p_motor'));
               }
        }
        function guardar(){
            if (!empty($this->data['Vehicles'])){
                        $this->Master->Vehicles->create();
                        $this->log('vehicle antesd de save');
                        if ($this->Master->Vehicles->save($this->data)) {
                                $this->data['Master']['vehicles_id'] = $this->Master->Vehicles->getLastInsertId();
                                $this->log('vehicle despues de save');
                                //$this->data['Master']['rodamiento'] = $this->data['Vehicles']['rodamiento'];
			}else{
                            $this->log('vehicle return false');
                               return false;
			}
                    }
                    if (!empty($this->data['Causes']['nro_causa'])) {
                         $this->Master->Causes->create();
                                if ($this->Master->Causes->save($this->data)) {
                                $this->log('Causa salvada');
                                $this->data['Master']['causes_id'] = $this->Master->Causes->getLastInsertId();
			}else{
                            $this->log('Causa no salvada');
                        } 
                     }
                     if($this->data['Master']['causes_id'] && $this->data['Master']['vehicles_id']&& $this->valida_imagenes()){
                     $this->log('antes de create Master');
                         $this->Master->create();
                     $date = getdate();
                     $parafecha = explode("-", $this->data['Master']['date']);
                     $this->data['Master']['fecha']['year'] = $parafecha['0']; 
                     $this->data['Master']['fecha']['month'] = $parafecha['1'];
                     $this->data['Master']['fecha']['day'] = $parafecha['2'];
                     $this->data['Master']['fecha_registro'] =  $date['year'].'-'.$date['mon'].'-'.$date['mday'].' '.$date['hours'].':'.$date['minutes'].':'.$date ['seconds'];
                     $user = $this->Session->read('Auth.User');
                     $this->data['Master']['user_id'] = $user['id'];                                        
			if ($this->Master->save($this->data)) {
                                $this->sube_imagenes();  
                                //aca salvar imagenes leyendo desde el servidor
				$this->Session->setFlash(__('The master has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
                                $this->redirect(array('action' => 'index'));
				$this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
			}
                     }else{
                         $this->Session->setFlash(__('Error en tipo de Imagen.', true));
                         $this->Session->setFlash(__('The master could not be saved. Please, try again.', true));
                         $provinces2 = $this->Province->find('list',array('fields'=>'descripcion','conditions'=> array('jurisdiction_id'=>$this->data['Master']['jurisdictions_id'])));
                         $provinces = $provinces2;
                         $this->set(compact('provinces'));
                         
                     }
   
        }
        function sube_img_server(){       
            //busco si viene el indice derecha
            if (array_key_exists('derecha', $_FILES)) {  
                //corto la cadena para controlar la extension del archivo
                $tipo_x = explode('/', $_FILES['derecha']['type']);
                $tipo_archivo = $tipo_x['1'];
                  if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['derecha']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);  
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['derecha']['tmp_name']);
                  //tipo_img = 1 significa q corresponde a la imagen 'derecha' para utilizar en la vista
                  $tipo_img = '1';
                  //tipo_archivo 0 si es permitido 1 si no es permitido, para validar en la vista
                  $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '1';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
            }
            if (array_key_exists('izquierda', $_FILES)) {  
                $tipo_x = explode('/', $_FILES['izquierda']['type']);
                $tipo_archivo = $tipo_x['1'];
                if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['izquierda']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);  
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['izquierda']['tmp_name']);
                  $tipo_img = '2';
                 $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '2';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
            }
             if (array_key_exists('frente', $_FILES)) {  
                $tipo_x = explode('/', $_FILES['frente']['type']);
                $tipo_archivo = $tipo_x['1'];
                if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['frente']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['frente']['tmp_name']);
                  $tipo_img = '3';
                  $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '3';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
            }
             if (array_key_exists('baul', $_FILES)) {  
                $tipo_x = explode('/', $_FILES['baul']['type']);
                $tipo_archivo = $tipo_x['1'];
                if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['baul']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['baul']['tmp_name']);
                  $tipo_img = '4';
                  $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '4';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
            }
            if (array_key_exists('interior', $_FILES)) {  
                $tipo_x = explode('/', $_FILES['interior']['type']);
                $tipo_archivo = $tipo_x['1'];
                if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['interior']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['interior']['tmp_name']);
                  $tipo_img = '5';
                  $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '5';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
            }
            if (array_key_exists('motor', $_FILES)) {
                $tipo_x = explode('/', $_FILES['motor']['type']);
                $tipo_archivo = $tipo_x['1'];
                if($tipo_archivo == 'JPG'|| $tipo_archivo == 'jpg' || $tipo_archivo == 'jpeg'){
                  $imagen = $_FILES;
                  $nombre_imagen = $_FILES['motor']['name'];
                  $nuevo_nombre = $this->cambiar_nombre_imagen($nombre_imagen);
                  $fileData = $this->resize_image($nuevo_nombre,$imagen['motor']['tmp_name']);
                  $tipo_img = '6';
                  $tipo_archivo = '0';
                  $this->set(compact('nombre_imagen','tipo_img','nuevo_nombre','tipo_archivo'));
                  }else{
                      $tipo_img = '6';
                      $tipo_archivo = '1';
                      $this->set(compact('tipo_archivo','tipo_img'));
                  }
                  $this->render('/masters/sube_img_server', 'ajax');
    
           }
        }
             function cambiar_nombre_imagen($nombre){
                $nombre_n = explode('.', $nombre);
                $ran = rand(5, 15);
                $user = $this->Session->read('User');
                //acá se genera un nombre de archivo formado por el nombre originl mas un nro random mas el id de usuario la idea es q sea irrepetible 
                $nombre_nuevo = $nombre_n['0'].$ran.$user['id'].".".$nombre_n['1']; 
                return $nombre_nuevo;
            }  
              
          
}
